<template>
  <div>
    <div style="margin-top:20px" class="qup-title-box"><span class="border" /><span>{{ configType?'配图配置最终信息': '配图配置信息' }}</span></div>

    <el-form
      ref="refForm"
      :rules="formRules"
      :model="formData"
      size="mini"
      label-width="150px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="业务类型:" size="mini" prop="businessType">
            <el-checkbox-group v-model="formData.businessType" @change="changeBusinessType">
              <el-checkbox v-for="item in businessTypeList" :key="item.dictCode" :label="item.dictName">{{ item.dictName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="定制面积:" prop="customizeArea">
            <el-input v-model.number="formData.customizeArea" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="橱柜面积:" prop="cabinetArea">
            <el-input v-model.number="formData.cabinetArea" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="回传外观时间:" prop="backFacadeTime">
            <el-input v-model="formData.backFacadeTime" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="定制自主设计占比:" prop="ownDesignPercent">
            <el-input v-model="formData.ownDesignPercent" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注:" prop="urgentRemark">
            <el-input v-model="formData.urgentRemark" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- <el-button size="mini" type="primary" @click="submitForm">保存</el-button>
    <el-button style="margin-right:20px" size="mini" type="primary" @click="handleCancel">取消</el-button> -->

    <el-table
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      show-overflow-tooltip
      border
      show-summary
      :summary-method="getSummaries"
      :data="formData.autonomyDesignBusinessDTOList"
      style="width: 90%"
    >
      <el-table-column prop="bizType" label="业务类型" min-width="100" />
      <el-table-column prop="productNum" label="产品个数" min-width="100">
        <template slot="header">
          <span style="color: red">*</span>产品个数
        </template>
        <template slot-scope="scope">
          <el-input v-model.number="scope.row.productNum" @change="(data)=>{if(data<(scope.row.productNum&&Number(scope.row.autonomyDesignNum))||0) scope.row.productNum=null}" />
        </template>
      </el-table-column>
      <el-table-column prop="autonomyDesignNum" label="自主设计数量" min-width="100">
        <template slot-scope="scope">
          <el-input v-model.number="scope.row.autonomyDesignNum" @change="(data)=>{if(data>(scope.row.productNum&&Number(scope.row.productNum))||0) scope.row.autonomyDesignNum=null}" />
        </template>
      </el-table-column>

    </el-table>
    <c-file-table-box v-model="shopAttachmentDTOList" type-code="ACCESS045" :table-height="250" belong-model="SELF_DESIGN" :model-id="$route.query.id" />

  </div>
</template>
<script>
import { submitFacadeBack } from '@/api/autoDesignTask'
import { getDictByPatchType } from '@/api/dataDict'
export default {
  name: 'DrawingEdit',
  components: {},
  props: {
    baseInfo: {
      type: Object,
      default: () => {},
      immediate: true
    },
    configType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      tempObj: {},
      formData: { autonomyDesignBusinessDTOList: [],
        backFacadeTime: '',
        customizeArea: '',
        cabinetArea: '',
        ownDesignPercent: '',
        urgent: '',
        urgentRemark: '',
        autonomyDesignId: '',
        configType: this.configType,
        businessType: [] },
      businessTypeList: [], // 业务类型
      shopAttachmentDTOList: [],
      formRules: {
        businessType: [{ required: true, message: '请选择', trigger: 'change' }],
        customizeArea: [{ required: true, message: '请填写', trigger: 'change' }],
        cabinetArea: [{ required: true, message: '请填写', trigger: 'change' }]
      }
    }
  },
  watch: {
    baseInfo: {
      handler(v) {
        this.shopAttachmentDTOList = JSON.parse(JSON.stringify(this.baseInfo.shopAttachmentDTOList || []))
        let businessType = ''
        if (v.drawingConfigDTOList && v.drawingConfigDTOList.length > 0) {
          let obj = []
          obj = v.drawingConfigDTOList.filter(v => v.configType === this.configType)
          if (this.configType === 1 && obj.length === 0) {
            obj = v.drawingConfigDTOList.filter(v => v.configType === 0)
            obj.length > 0 ? this.$set(obj[0], 'id', null) : ''
          }
          if (obj.length > 0) {
            businessType = obj[0].businessType
            const { backFacadeTime, customizeArea, cabinetArea, ownDesignPercent, urgentRemark, autonomyDesignId, id } = obj[0]
            this.formData = { backFacadeTime, customizeArea, cabinetArea, ownDesignPercent, urgentRemark, autonomyDesignId, id }
            this.$set(this.formData, 'autonomyDesignBusinessDTOList', JSON.parse(JSON.stringify(obj[0].autonomyDesignBusinessDTOList)))
            this.$set(this.formData, 'configType', this.configType)
            this.tempObj = this.formData
          } else {
            businessType = ''
            this.formData = { autonomyDesignBusinessDTOList: [],
              backFacadeTime: '',
              customizeArea: '',
              cabinetArea: '',
              ownDesignPercent: '',
              urgent: '',
              urgentRemark: '',
              autonomyDesignId: '',
              configType: this.configType }
          }
        } else {
          businessType = ''
        }
        this.$set(this.formData, 'businessType', (businessType && businessType.split(',') || []))
      },
      deep: true,
      immediate: true
    }
  },
  async created() {
    const { SLM_BUSINESS_TYPE } = await getDictByPatchType(['SLM_BUSINESS_TYPE'])
    this.businessTypeList = SLM_BUSINESS_TYPE
  },
  methods: {
    // 保存
    submitForm() {
      const { backFacadeTime, customizeArea, cabinetArea, ownDesignPercent, urgentRemark, autonomyDesignId, id } = this.tempObj
      const temp = { backFacadeTime, customizeArea, cabinetArea, ownDesignPercent, urgentRemark, autonomyDesignId, id }
      const submitData = { id: this.$route.query.id,
        drawingConfigDTOList: [{
          ...temp,
          autonomyDesignBusinessDTOList: this.formData.autonomyDesignBusinessDTOList }] }
      return
      submitFacadeBack(submitData, 0).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
        }
      })
    },
    handleCancel() {
      this.formData.autonomyDesignBusinessDTOList = this.baseInfo.autonomyDesignBusinessDTOList || []
    },
    changeBusinessType(data) {
      if (data.length === 0) {
        this.$set(this.formData, 'ownDesignPercent', '0')
      }
      const flag1 = this.formData.autonomyDesignBusinessDTOList.filter(item => {
        const index = data.findIndex(i => i === item.bizType)
        return index !== -1
      })
      const flag2 = data.filter(item => {
        const index = this.formData.autonomyDesignBusinessDTOList.findIndex(i => i.bizType === item)
        return index === -1
      })
      let flag3 = this.businessTypeList.filter(item => {
        const index = flag2.findIndex(i => i === item.dictName)
        return index !== -1
      })
      flag3 = flag3.map(v => { return { bizType: v.dictName, bizTypeCode: v.dictCode } })
      this.formData.autonomyDesignBusinessDTOList = [...flag1, ...flag3]
    },
    designPercentCount(arr) {
      const list = arr.filter(v => v.bizType === '全屋定制' || v.bizType === '多功能墙面')
      const arr1 = list.map(v => Number(v.autonomyDesignNum || 0))
      const arr2 = list.map(v => Number(v.productNum || 0))
      if (list.length === 0) {
        this.$set(this.formData, 'ownDesignPercent', '0')
        return
      }
      const total1 = arr1.reduce((prev, curr) => {
        // const value = Number(curr)
        if (!isNaN(curr)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      const total2 = arr2.reduce((prev, curr) => {
        // const value = Number(curr)
        if (!isNaN(curr)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      this.$set(this.formData, 'ownDesignPercent', ((total1 / total2) * 100).toFixed(0) + '%')
    },
    getSummaries(param) {
      const { columns, data } = param
      this.designPercentCount(param && param.data)
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ' 个'
        } else {
          sums[index] = 'N/A'
        }
      })

      return sums
    },
    // 向父组件返回保存或提交的数据
    submitData() {
      return new Promise((resolve, reject) => {
        this.$refs.refForm.validate((valid) => {
          if (valid) {
            const temp = this.formData.autonomyDesignBusinessDTOList.filter(v => !v.productNum)
            if (temp.length > 0) {
              this.$message.warning('请完善业务类型的产品个数填写')
              resolve(false)
              return
            }
            this.$set(this.formData, 'businessType', this.formData.businessType.join(','))
            const fileList = this.shopAttachmentDTOList.map(v => {
              return v.response ? v.response.data : v
            })
            const list = this.baseInfo.drawingConfigDTOList.filter(v => v.configType !== this.configType)
            list.push(this.formData)
            const submitData = { drawingConfigDTOList: list, id: this.baseInfo.id, shopAttachmentDTOList: fileList }
            resolve(submitData)
          } else {
            resolve(false)
          }
        })
      })
    }
  }
}
</script>
